// miniprogram/pages/bianji/bianji.js
const app = getApp()
const db = wx.cloud.database()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgList: [],
    fileIDs: [],
    show: false,

    xinwendata: ['普通用户', "医院"],
    diqudata: ['广东', "山西"],

    message: '',
    xinwentype: '普通用户',
    diqutype: '广东'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },


  onChangename(event) {
    this.setData({
      name: event.detail
    })
  },
  onChangezh(event) {
    this.setData({
      zhanghao: event.detail
    })
  },
  onChangemima(event) {
    this.setData({
      mima: event.detail
    })
  },
  onChangephone(event) {
    this.setData({
      phone: event.detail
    })
  },




  //选择
  onChangexinwen(event) {
    this.setData({
      xinwentype: event.detail.value,
      xinwenpd: false,
      show: false
    });
  },

  oncancelxinwen() {
    this.setData({
      xinwenpd: false,
      show: false
    })
  },

  chosexinwen() {
    this.setData({
      xinwenpd: true,
      show: true
    })
  },

  //地区选择
  onChangediqu(event) {
    this.setData({
      diqutype: event.detail.value,
      diqupd: false,
      show: false
    });
  },

  oncanceldiqu() {
    this.setData({
      diqupd: false,
      show: false
    })
  },

  chosediqu() {
    this.setData({
      diqupd: true,
      show: true
    })
  },

  onLoad(option) {
    console.log(option)
    this.setData({})
  },



  onChangea(event) {
    this.setData({
      title: event.detail
    })
  },


  // 选择图片
  ChooseImage() {
    wx.chooseImage({
      count: 9, //默认9,我们这里最多选择8张
      sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log("选择图片成功", res)
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    })
  },

  //删除图片
  DeleteImg(e) {
    console.log("e", e.currentTarget.dataset.index)
    this.data.imgList.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      imgList: this.data.imgList
    })
  },

  //上传数据
  publish() {
    const title = this.data.title
    const xinwentype = this.data.xinwentype
    const diqu = this.data.diqutype
    let d = new Date()
    if (!title) {
      wx.showToast({
        title: '请输入名字',
        icon: 'none'
      })
    } 

    else if (!xinwentype) {
      wx.showToast({
        title: '选择类型',
        icon: 'none'
      })
    }
    else if (!this.data.zhanghao) {
      wx.showToast({
        title: '选择输入账号',
        icon: 'none'
      })
    }
    else if (!this.data.mima) {
      wx.showToast({
        title: '选择输入密码',
        icon: 'none'
      })
    }
    else if (!this.data.phone) {
      wx.showToast({
        title: '选择输入手机号',
        icon: 'none'
      })
    }
    else if (!diqu) {
      wx.showToast({
        title: '选择地区',
        icon: 'none'
      })
    }

    else if (this.data.imgList.length === 0) {
      wx.showToast({
        title: '请上传图片资料',
        icon: 'none'
      })
    } else

    {
      /*文本内容安全检测 */
      const Promise_arr = [];
      Promise.all(Promise_arr).then(res => {
        wx.showLoading({
          title: '提交中....',
        })
        const promiseArr = []
        //只能一张张上传 遍历临时的图片数组
        for (let i = 0; i < this.data.imgList.length; i++) {
          let filePath = this.data.imgList[i]
          let suffix = /\.[^\.]+$/.exec(filePath)[0]; // 正则表达式，获取文件扩展名
          //在每次上传的时候，就往promiseArr里存一个promise，只有当所有的都返回结果时，才可以继续往下执行
          promiseArr.push(new Promise((reslove, reject) => {
            wx.cloud.uploadFile({
              cloudPath: 'myimages/' + new Date().getTime() + suffix,
              filePath: filePath, // 文件路径
            }).then(res => {
              // get resource ID
              console.log("上传结果", res.fileID)
              this.setData({
                fileIDs: this.data.fileIDs.concat(res.fileID)
              })
              reslove()
            }).catch(error => {
              console.log("上传失败", error)
            })
          }))
        }
        //保证所有图片都上传成功
        Promise.all(promiseArr).then(res => {
          var d = new Date(); {
            db.collection('users').add({
              data: {
                userPhoto :'cloud://cloud1-7ge3r2d44d1ee4ba.636c-cloud1-7ge3r2d44d1ee4ba-1310918076/头像.png',
                zhanghao:this.data.zhanghao,
                mima:this.data.mima,
                phone:this.data.phone,
                diqu,
                xinwentype,
                nickName:title,
                fileIDs: this.data.fileIDs,
                createtime: d.getFullYear() + ' ' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds(),
                time_order: new Date().getTime(),
                type: '待审核'
              },
              success: res => {
                wx.hideLoading()
                if (res._id) {
                  wx.showToast({
                    title: '提交成功',
                  })
                  console.log('提交成功', res)
                  // wx.switchTab({
                  //   url: '../daishenhe/index',
                  // })
                  wx.redirectTo({
                    url: '../daishenhe/index',
                  })
                }
              },
              fail: err => {
                wx.hideLoading()
                wx.showToast({
                  icon: 'none',
                  title: '网络不给力....'
                })
                console.error('发布失败', err)
              }
            })
          }
        })
      }).catch(res => {

      })
    }
  },
  baocun() {


    let that = this
    var d = new Date();
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于获取微信信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        let userInfo = res.userInfo

        if (!that.data.name) {
          wx.showToast({
            title: '请输入名字',
            icon: 'none'
          })
        } 
    
        else if (!that.data.xinwentype) {
          wx.showToast({
            title: '选择类型',
            icon: 'none'
          })
        }
        else if (!that.data.zhanghao) {
          wx.showToast({
            title: '选择输入账号',
            icon: 'none'
          })
        }
        else if (!that.data.mima) {
          wx.showToast({
            title: '选择输入密码',
            icon: 'none'
          })
        }
        else if (!that.data.phone) {
          wx.showToast({
            title: '选择输入手机号',
            icon: 'none'
          })
        }
        else 
{        db.collection('users').add({
          data: {
            zhanghao:that.data.zhanghao,
            mima:that.data.mima,
            phone:that.data.phone,
            userPhoto: userInfo.avatarUrl,
            nickName: that.data.name,
            createtime: d.getFullYear() + ' ' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds(),
            time_order: new Date().getTime(),
            type: '已审核',
            xinwentype:that.data.xinwentype
          }
        }).then((res) => {

    
          wx.reLaunch({
            url: '../shouye/index',
          })


        })}



      }
    })
    // console.log(ev);
  },

})